<?php
class Core
{
	// Объект текущего юзера
	public static $user;
	// Текущий Контроллер
	public static $controller;
	// Текущий метод
	public static $method;
	public static $origin;
	public static $api = Array();
	// Текущий
	public static $isAjax = false;
	public static $ajax	  = Array();
	public static $main_content = "";
	public static $error = Array();
	public static $blocks_content = Array();
	
	public static $chat_client;
	public static function ChatClient(){
		if(self::$chat_client == null){
			self::$chat_client = new clientChat();
		}
		return self::$chat_client;
	}
	

	public static function GetRealIp(){
		$ip = "";
		if ($_SERVER['HTTP_CLIENT_IP']) {
			$ip.= $_SERVER['HTTP_CLIENT_IP']."::";
		}
		if($_SERVER['HTTP_X_FORWARDED_FOR']){
			$ip.= $_SERVER['HTTP_X_FORWARDED_FOR']."::";
		}
		$ip.= $_SERVER['REMOTE_ADDR'];
		
		return $ip;
	}
	
	public static function setupUser(){
	//	DB::createClassFromDB("ava_dau");
	// Если зашли по промо ссылке
		if($_REQUEST["promo"] > 0){
			setcookie('promo_id', $_REQUEST["promo"],  time()+ 3600 * 24 * 10, "/", ".townwars.ru");	
		}
	
	//	self::ChatClient()->reloadChannels();
		// Если есть юзер ID в сессии
		if( $_SESSION["user_id"] > 0){
			$time = time();	
			setcookie('authKey', 	md5($_SESSION["user_id"]."XUXP8Umg12PrevolnadDa".$time) , $time + 3600, "/", ".townwars.ru");
			setcookie('authId', 	$_SESSION["user_id"] ,$time + 3600, "/", ".townwars.ru");
			setcookie('authTime', 	$time , $time + 3600, "/", ".townwars.ru");
			//$this->user = Worker::fetchObject(wj_users, array("id" => $_SESSION["user_id"]));
		# Дергаем сегодняшний день
			$cur_date = date("Y-m-d 00:00:00");																						
		}else{
	// Если есть подъемная кука
			if( !empty($_COOKIE["tw_session"]) && !empty($_COOKIE["tw_time"]) ){
				
				/*$query = new Query();
				$query->field("session", $_COOKIE["tw_session"]);
				$s = Worker::fetchObjectByFields("ava_user_session", $query);
				if($s instanceof ava_user_session){
					if($s->session == md5(md5( core::GetRealIp() . $s->user_id . $_SERVER['HTTP_USER_AGENT']).$_COOKIE["tw_time"])){
						$_SESSION["user_id"] = $s->user_id;
					}else{
						setcookie('tw_session', "" , $time, "/", ".townwars.ru");
						setcookie('tw_time', "" , $time, "/", ".townwars.ru");
					}
				}else{
					setcookie('tw_session', "" , $time, "/", ".townwars.ru");
					setcookie('tw_time', "" , $time, "/", ".townwars.ru");
				}*/
			}
		}
	}
	
	
	
	
	
	/**
	* Настройка  контроллеров
	*/
	public static function setup(){
		self::setupUser();		
		
		CoreConfig::addController( new CoreConfigController("Index", "Index",   "Index", false));		
		
        if(isset($_SESSION["user_view"])){   
            self::$user = Worker::fetchObject( "wj_users", Array("id" => $_SESSION["user_view"]) );
            if (self::$user instanceof wj_users)
            {
                self::$user->readonly = 1;
            }
        }
        
		if(isset($_SESSION["user_id"])){
			
			
			self::$user = Worker::fetchObject( "wj_users", Array("id" => $_SESSION["user_id"]) );
            if (self::$user instanceof wj_users)
            {
                self::$user->readonly = 0;
            }
			/*
			if(self::$user instanceof ava_users)
			{
				$time = time();		
				//setcookie('userName', 	self::$user->name , $time() + 3600 * 24 * 3 );
				//setcookie('userLevel', 	self::$user->data->level , $time() + 3600 * 24 * 3);
				//setcookie('userRace', 	self::$user->race , $time() + 3600 * 24 * 3);
				// Обновляем статс онлайна пользователя
				if( ($res = DB::getMCH()->get("AVA:Online:" . self::$user->id)) === false){
					DB::getMCH()->set("AVA:Online:" . self::$user->id, 1, 0, 600);
				}else{
					DB::getMCH()->replace("AVA:Online:" . self::$user->id, 1, 0, 600);
				}
				
				if( (time() - $_SESSION["tw_last_time_online"]) > (5 * 60) ){
					DB::UserOnlineIn();
				}
				// Дополнительные контроллеры
				switch(self::$user->status){
					// Администраторы				
					case(3):
						// Контролы в стадии тестирования
						// Админ модули
						
						CoreConfig::addController( new CoreConfigController("AdminMenu", 		"Index", 	"Admin") );
						CoreConfig::addController( new CoreConfigController("AdminNews", 		"Index", 	"Admin", true, array("AdminMenu")) );
						CoreConfig::addController( new CoreConfigController("AdminProperty", 	"Index", 	"Admin", true, array("AdminMenu")) );
						CoreConfig::addController( new CoreConfigController("AdminPerk", 	"Index", 	"Admin", true, array("AdminMenu")) );
						CoreConfig::addController( new CoreConfigController("AdminContragents", 	"Index", 	"Admin", true, array("AdminMenu")) );
						CoreConfig::addController( new CoreConfigController("AdminLocation", 	"Index", 	"Admin", true, array("AdminMenu")) );
						CoreConfig::addController( new CoreConfigController("AdminQuest", 	"Index", 	"Admin", true, array("AdminMenu")) );
						CoreConfig::addController( new CoreConfigController("AdminClan", 	"Index", 	"Admin", true, array("AdminMenu")) );

						CoreConfig::addController( new CoreConfigController("AdminStats", 	"Index", 	"Admin", true, array("AdminMenu")) );
						CoreConfig::addController( new CoreConfigController("AdminCurrency", 	"Index", 	"Admin", true, array("AdminMenu")) );
						CoreConfig::addController( new CoreConfigController("AdminExptable", 	"Index", 	"Admin", true, array("AdminMenu")) );
						CoreConfig::addController( new CoreConfigController("AdminInstance", 	"Index", 	"Admin", true, array("AdminMenu")) );
						
						CoreConfig::addController( new CoreConfigController("AdminItems", 		"Index", 	"Admin", true, array("AdminMenu")) );
						CoreConfig::addController( new CoreConfigController("AdminFarm", 		"Index", 	"Admin", true, array("AdminMenu")) );
						CoreConfig::addController( new CoreConfigController("AdminTerritory", 		"Index", 	"Admin", true, array("AdminMenu")) );
						CoreConfig::addController( new CoreConfigController("AdminPersonage", 	"Index", 	"Admin", true, array("AdminMenu")) );
						CoreConfig::addController( new CoreConfigController("AdminAchievments", 	"Index", 	"Admin", true, array("AdminMenu")) );
						CoreConfig::addController( new CoreConfigController("AdminBandNPC", 	"Index", 	"Admin", true, array("AdminMenu")) );
						CoreConfig::addController( new CoreConfigController("AdminInstance", 	"Index", 	"Admin", true, array("AdminMenu")) );
						CoreConfig::addController( new CoreConfigController("Statistica", 	"Index", 	"Admin", true, array("AdminMenu")) );
						CoreConfig::addController( new CoreConfigController("AdminCraft", 		"Index", 	"Admin", true, array("AdminMenu")) );
						CoreConfig::addController( new CoreConfigController("AdminPromo", 		"Index", 	"Admin", true, array("AdminMenu")) );
						CoreConfig::addController( new CoreConfigController("AdminAvatar", 		"Index", 	"Admin", true, array("AdminMenu")) );
						CoreConfig::addController( new CoreConfigController("AdminPreceptorship", "Index", 	"Admin", true, array("AdminMenu")) );
						CoreConfig::addController( new CoreConfigController("AdminPages", 	"Index", 	"Admin",  		true, array("AdminMenu")));
						CoreConfig::addController( new CoreConfigController("AdminCollection",	"Index", 	"Admin", 	true, array("AdminMenu")));
						CoreConfig::addController( new CoreConfigController("AdminPatrol",	"Index", 	"Admin", 	true, array("AdminMenu")));
						CoreConfig::addController( new CoreConfigController("AdminSupport",	"Index", 	"Admin", 	true, array("AdminMenu")));
						CoreConfig::addController( new CoreConfigController("AdminAwardPerDay",	"Index", 	"Admin", 	true, array("AdminMenu")));
						CoreConfig::addController( new CoreConfigController("AdminRaceBonus",	"Index", 	"Admin", 	true, array("AdminMenu")));

					case(2):
					// Модераторы
						//CoreConfig::addController( new CoreConfigController("AdminMenu", 		"Index", 	"Admin") );
						CoreConfig::addController( new CoreConfigController("Chatadmin", "Index", "Admin", true, array("AdminMenu" )) );						
						CoreConfig::addController( new CoreConfigController("AdminFiles", 		"Index", 	"Admin", true, array("AdminMenu")) );						
						CoreConfig::addController( new CoreConfigController("AdminReferal", 		"Index", 	"Admin", true, array("AdminMenu")) );												
						CoreConfig::addController( new CoreConfigController("AdminPages", 	"Index", 	"Admin",  		true, array("AdminMenu")));												
										
					break;
					// Заблокированные
					case(0):
						CoreConfig::addController( new CoreConfigController("Blocked", "Index", "Empty") );
						$_REQUEST["c"] = "Blocked";
						unset($_REQUEST["m"]);
					break;
				}
				
				
			}*/
		}
                
		
		if( isset( $_SESSION["origin"] ) ){
			self::$origin = $_SESSION["origin"];
		}
		if( !empty( $_SESSION["api"] ) ){
			self::setSocialApi( $_SESSION["api"] );
		}
		// Загружаемый контроллер
		self::$controller = ( isset($_REQUEST["c"]) ) ? CoreConfig::getController( $_REQUEST["c"] )  : CoreConfig::getController( CoreConfig::$defaultController );
		self::$method = ( isset($_REQUEST["m"]) ) ? $_REQUEST["m"] : self::$controller->dMethod;
		self::$isAjax = ($_REQUEST["ajax"]) ? true : false;		
	}

	public static function setSocialApi($api){
		self::$api = $api;
		$_SESSION["api"] = $api;
	}


	/**
	* Вызов контроллера
	*/
	public static function execController(){
		$class_name = self::$controller->class_name;
		$folder_name = CFG_CONTROL_CLASSES.DIRECTORY_SEPARATOR.$class_name;
      	$class_name .= "_controller";
      	$controller_file = $folder_name.DIRECTORY_SEPARATOR.$class_name.".php";
      	if(file_exists($controller_file)){
			require($controller_file);
      		$controller = new $class_name($folder_name);
      		$controller->getMethod( self::$method );
      		self::$main_content = $controller->Content;
      		if(self::$isAjax){
      			self::$ajax = $controller->ajax;
      		}
      		if($controller->Error != null){
      			array_push(self::$error, Array("cname" => self::$controller->name,"cmethod" => self::$method, "error" => $controller->Error));
      		}
      		if( method_exists( $controller, "getMetaTitle" ) ){
      			
      		}
      	}

	}
	
	public static function getControl($contol, $param = Array()){
		$class_name = CoreConfig::getController( $contol )->class_name;
		$folder_name = CFG_CONTROL_CLASSES.DIRECTORY_SEPARATOR.$class_name;
      	$class_name .= "_controller";
      	$controller_file = $folder_name.DIRECTORY_SEPARATOR."$class_name.php";
      	if(file_exists($controller_file)){
      		//if(!class_exists($class_name)){
				require_once($controller_file);
      		//}
			//
      		$controller = new $class_name( $folder_name );
      		$controller->setControlParam( $param );
      		//$controller->getMethod( $method );
      		return $controller;
      	}else{
      		return false;
      	}
	}
	

	public static function getBlocks(){
		if( !empty( self::$controller->blocks) ){
			foreach(self::$controller->blocks as $block_name){
				$block = CoreConfig::getController( $block_name );
				$class_name = $block->class_name;
				$folder_name = CFG_CONTROL_CLASSES.DIRECTORY_SEPARATOR.$class_name;
      			$class_name .= "_controller";
      			$controller_file = $folder_name.DIRECTORY_SEPARATOR."$class_name.php";
      			if(file_exists($controller_file)){
					require_once($controller_file);
					$controller = new $class_name($folder_name);
      				$controller->getMethod( $block->dMethod );
      				self::$blocks_content[]["data"] = $controller->Content;

      				if($controller->Error != null){
      					array_push(self::$error, Array("cname" => self::$controller->name,"cmethod" => self::$method, "error" => $controller->Error));
      				}
				}
			}
		}
	}

	public static function getSocialApi(){
		$apiname = "SocialOrigin_".self::$origin;
    	$api 	 = new $apiname( self::$api );
    	return $api;
	}

	public static function execAjaxController(){

	}

	public static function getContent(){
		if(!self::$isAjax){
			$tmpl_path = CFG_PATH_HTDOCS . DIRECTORY_SEPARATOR . "templates" . DIRECTORY_SEPARATOR . self::$controller->template . DIRECTORY_SEPARATOR . "Index.html";
			$tmpl = new vlibTemplate($tmpl_path);
			$tmpl->setvar("CFG_HOST_IMG", CFG_HOST_IMG);
			$folders = array();
			if ( core::$user instanceof wj_users ) {				
                if (core::$user->readonly != 1)
                {
				    $tmpl->setVar('user_authenticated', true);												
                }
      		}      		      		
			$tmpl->setvar( "serverTime", time());
			$tmpl->setvar( "content", self::$main_content);
			if(!empty(self::$error)){
				$tmpl->setloop( "CoreError", self::$error );
			}
			self::getBlocks();
			$tmpl->setLoop("Blocks", self::$blocks_content);


			return $tmpl->grab();
		}else{
			$res["error"] = self::$main_content;
			$res["result"]  = self::$ajax;
			//$res["debug"]  = Worker::$_worker_stat;
			return $res;
		}
	}


}
?>